package cn.congine.wizarpos.mall.dao.hibernate;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import cn.congine.wizarpos.mall.dao.SysWxChildMerchantTokenDao;
import cn.congine.wizarpos.mall.model.SysWxChildMerchantToken;

@Repository("sysWxChildMerchantTokenDao")
public class SysWxChildMerchantTokenDaoHibernate extends GenericDaoHibernate<SysWxChildMerchantToken> implements SysWxChildMerchantTokenDao {

	public SysWxChildMerchantTokenDaoHibernate() {
		super(SysWxChildMerchantToken.class);
	}

	/**
	 * 更新授权商户微信access token
	 * 
	 * @param t
	 * @return
	 */
	public int update(
			String mid,
			String authorizer_access_token,
			long authorizer_access_token_expiry,
			String authorizer_refresh_token,
			String id){
		String sql = "UPDATE sys_wx_child_merchant_token SET "
				+ "authorizer_access_token=:authorizer_access_token,"
				+ "authorizer_access_token_expiry=:authorizer_access_token_expiry,"
				+ "authorizer_refresh_token=:authorizer_refresh_token"
				+ " WHERE mid=:mid and id=:id";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createSQLQuery(sql);
		q.setParameter("authorizer_access_token", authorizer_access_token);
		q.setParameter("authorizer_access_token_expiry", authorizer_access_token_expiry);
		q.setParameter("authorizer_refresh_token", authorizer_refresh_token);
		q.setParameter("mid", mid);
		q.setParameter("id", id);
		return q.executeUpdate();
	}

	/**
	 * 更新非授权商户微信access token
	 * 
	 * @param t
	 * @return
	 */
	public int updateMrtToken(SysWxChildMerchantToken t){
		String sql = "UPDATE sys_wx_child_merchant_token SET "
				+ "merchant_access_token=:merchant_access_token,"
				+ "merchant_access_token_expiry=:merchant_access_token_expiry"
				+ " WHERE mid=:mid and id=:id";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		
		Query q = getSession().createSQLQuery(sql);
		
		q.setParameter("merchant_access_token", t.getMerchantAccessToken());
		q.setParameter("merchant_access_token_expiry", t.getMerchantAccessTokenExpiry());
		q.setParameter("mid", t.getMid());
		q.setParameter("id", t.getId());
		
		return q.executeUpdate();
	}
	
	public SysWxChildMerchantToken getByMid(String mid){
		Query query = getSession().createQuery(
				"from SysWxChildMerchantToken where mid =:mid").setParameter("mid",	mid);
		return (SysWxChildMerchantToken) query.uniqueResult();
	}

	@Override
	public SysWxChildMerchantToken findByGhCode(String gh) {
		Query query = getSession().createQuery(
				"from SysWxChildMerchantToken where ghCode =:gh").setParameter("gh", gh);
		return (SysWxChildMerchantToken) query.uniqueResult();
	}
}
